<template>
  <el-card class="electric-analysis-wrapper card-header">
    <header>
      <div class="head">
        <div class="head-icon">
          <svg-icon icon-class="dashboard-4"></svg-icon>
        </div>
        <div>电量电费分析</div>
      </div>
      <div><XyTimePicker></XyTimePicker></div>
    </header>
    <div class="data-energy-container" ref="chartContainer"></div>
    <div class="analysis-wrapper electricity-consumption">
      <header>电量电费分析</header>
      <main>
        <div class="main-left">
          <div>今日数据:</div>
          <div>
            <svg-icon icon-class="dot"></svg-icon>最高电量:1.8kWh(14:00-15:00)
          </div>
          <div>
            <svg-icon icon-class="dot"></svg-icon>最低电量:0.3kWh(03:00-04:00)
          </div>
          <div><svg-icon icon-class="dot"></svg-icon>平均电量:0.77kWh/小时</div>
        </div>
        <div class="main-right">
          <div>昨日数据:</div>
          <div>
            <svg-icon icon-class="dot"></svg-icon>最高电量:1.6kWh(15:00-16:00)
          </div>
          <div>
            <svg-icon icon-class="dot"></svg-icon>最低电量:0.2kWh(02:00-03:00)
          </div>
          <div><svg-icon icon-class="dot"></svg-icon>平均电量:0.68kWh/小时</div>
        </div>
      </main>
    </div>
  </el-card>
</template>

<script>
import XyTimePicker from "@/components/XyTimePicker.vue";
import * as echarts from "echarts";

export default {
  components: {
    XyTimePicker,
  },
  data() {
    return {
      chart: null,
    };
  },
  mounted() {
    this.initChart();
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose();
      window.removeEventListener("resize", this.resizeChart);
    }
  },
  methods: {
    initChart() {
      this.$nextTick(() => {
        const chartDom = this.$refs.chartContainer;
        if (chartDom) {
          this.chart = echarts.init(chartDom);
          this.setChartOption();
          window.addEventListener("resize", this.resizeChart);
        }
      });
    },

    setChartOption() {
      // 生成时间标签（24小时）
      const labels = [];
      for (let i = 0; i < 24; i++) {
        labels.push(`${i}:00`);
      }

      // 生成今日和昨日电量数据
      const todayEnergyData = this.getRandomData(24, 0.2, 2.0);
      const yesterdayEnergyData = todayEnergyData.map(
        (val) => val * (0.8 + Math.random() * 0.2)
      );

      // 计算电费数据（假设电价为0.5元/kWh）
      const todayCostData = todayEnergyData.map((val) => val * 0.5);
      const yesterdayCostData = yesterdayEnergyData.map((val) => val * 0.5);

      const option = {
        color: ["#10B981", "#9CA3AF", "#EF4444", "#6B7280"],
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
          },
          formatter: (params) => {
            let tooltipText = `${params[0].axisValueLabel}<br/>`;
            params.forEach((param) => {
              if (param.seriesIndex === 0 || param.seriesIndex === 1) {
                tooltipText += `${param.marker} ${param.seriesName}: ${param.value} kWh<br/>`;
              } else {
                tooltipText += `${param.marker} ${
                  param.seriesName
                }: ¥${param.value.toFixed(2)}<br/>`;
              }
            });
            return tooltipText;
          },
        },
        legend: {
          data: ["今日电量", "昨日电量", "今日电费", "昨日电费"],
          top: "top",
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          top: "20%",
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            data: labels,
            axisTick: {
              alignWithLabel: true,
            },
            axisLabel: {
              color: "#9498a1",
              margin: 10,
              fontSize: 11,
            },
            axisLine: {
              lineStyle: {
                color: "rgba(148, 163, 184, 0.2)",
              },
            },
          },
        ],
        yAxis: [
          {
            type: "value",
            name: "电量 (kWh)",
            nameTextStyle: {
              color: "#9498a1",
              padding: [0, 0, 0, 40],
              fontSize: 11,
            },
            splitLine: {
              lineStyle: {
                color: "rgba(148, 163, 184, 0.1)",
              },
            },
            axisLabel: {
              color: "#9498a1",
              fontSize: 11,
            },
            axisTick: {
              show: false,
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: "rgba(148, 163, 184, 0.2)",
              },
            },
          },
          {
            type: "value",
            name: "电费 (元)",
            nameTextStyle: {
              color: "#9498a1",
              padding: [0, 0, 0, 0],
              fontSize: 11,
            },
            splitLine: {
              show: false,
            },
            axisLabel: {
              color: "#9498a1",
              fontSize: 11,
              formatter: (value) => {
                return "¥" + value.toFixed(2);
              },
            },
            axisTick: {
              show: false,
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: "rgba(148, 163, 184, 0.2)",
              },
            },
          },
        ],
        series: [
          {
            name: "今日电量",
            type: "bar",
            data: todayEnergyData,
            yAxisIndex: 0,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "rgba(16, 185, 129, 0.8)" },
                { offset: 1, color: "rgba(16, 185, 129, 0.4)" },
              ]),
              borderColor: "rgba(16, 185, 129, 1)",
              borderWidth: 1,
              borderRadius: [4, 4, 0, 0],
            },
            barWidth: 12,
            barGap: "30%",
          },
          {
            name: "昨日电量",
            type: "bar",
            data: yesterdayEnergyData,
            yAxisIndex: 0,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "rgba(156, 163, 175, 0.6)" },
                { offset: 1, color: "rgba(156, 163, 175, 0.3)" },
              ]),
              borderColor: "rgba(156, 163, 175, 1)",
              borderWidth: 1,
              borderRadius: [4, 4, 0, 0],
            },
            barWidth: 12,
            barGap: "30%",
          },
          {
            name: "今日电费",
            type: "line",
            data: todayCostData,
            yAxisIndex: 1,
            itemStyle: {
              color: "#EF4444",
            },
            lineStyle: {
              width: 2,
            },
            smooth: true,
            showSymbol: true,
            symbol: "circle",
            symbolSize: 8,
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "rgba(239, 68, 68, 0.1)" },
                { offset: 1, color: "rgba(239, 68, 68, 0)" },
              ]),
            },
          },
          {
            name: "昨日电费",
            type: "line",
            data: yesterdayCostData,
            yAxisIndex: 1,
            itemStyle: {
              color: "#6B7280",
            },
            lineStyle: {
              width: 2,
              type: "dashed",
            },
            smooth: true,
            showSymbol: true,
            symbol: "circle",
            symbolSize: 8,
          },
        ],
      };

      this.chart.setOption(option);
    },

    // 生成随机数据的工具函数
    getRandomData(count, min, max) {
      return Array.from({ length: count }, () =>
        parseFloat((Math.random() * (max - min) + min).toFixed(2))
      );
    },

    resizeChart() {
      if (this.chart) {
        setTimeout(() => {
          this.chart.resize();
        }, 100);
      }
    },
  },
};
</script>

<style scoped lang="scss">
@import "./styles/common.scss";
.electric-analysis-wrapper.card-header {
  .head {
    .head-icon {
      background-color: #dcfcec;
      color: #16a34a;
    }
  }
  .data-energy-container {
    width: 100%;
    height: 400px;
    margin: 15px 0;
  }
  .electricity-consumption {
    width: 100%;
    color: #166534;
    background-color: rgba(240, 253, 244, 1);
    main {
      margin-top: 10px;
      display: flex;
      .main-left,
      .main-right {
        width: 50%;
        padding: 10px;
      }
    }
  }
}
</style>
